//
//  ViewController.m
//  Archive
//
//  Created by LiuZi on 2021/2/19.
//

#import "ViewController.h"
@interface ViewController()<NSOpenSavePanelDelegate>
@property (weak) IBOutlet NSTextField *projectPath;
@property (weak) IBOutlet NSButton *projectBtn;
@property (weak) IBOutlet NSTextField *cerPath;
@property (weak) IBOutlet NSButton *cerBtn;
@property (weak) IBOutlet NSTextField *outPath;
@property (weak) IBOutlet NSButton *outBtn;
@property (weak) IBOutlet NSPopUpButton *enviromentBtn;
@property (weak) IBOutlet NSButton *archiveBtn;

@property(nonatomic,retain)NSString *projectPathStr;
@property(nonatomic,retain)NSString *projectNameStr;
@property(nonatomic,retain)NSString *cerPathStr;
@property(nonatomic,retain)NSString *outPathStr;
@property(nonatomic,retain)NSURL *currentUrl;
@property(nonatomic,assign)int currentType;
@property(nonatomic,retain)NSTask *currentTask;
@property (weak) IBOutlet NSScrollView *scrollV;

@property (strong) NSTextView *text;

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [_enviromentBtn removeAllItems];
    [_enviromentBtn addItemWithTitle:@"debug"];
    [_enviromentBtn addItemWithTitle:@"release"];

    // Do any additional setup after loading the view.
    _text = [[NSTextView alloc] initWithFrame:_scrollV.bounds];
    [_scrollV setDocumentView:_text];;
}


- (IBAction)selectProject:(id)sender {
    _currentType = 1;
    NSOpenPanel *panel = [[NSOpenPanel alloc] init];
    panel.canChooseDirectories = YES;
    panel.title = @"选取项目路径";
    panel.delegate = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Desktop"]];
    panel.directoryURL = url;
    panel.backgroundColor = NSColor.whiteColor;
    __weak typeof(self) weakSelf = self;
    [panel beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:^(NSModalResponse returnCode) {
        if (returnCode==1) {
            weakSelf.projectPathStr = weakSelf.currentUrl.path;
            weakSelf.projectPath.stringValue = weakSelf.projectPathStr;
          NSArray *aa = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:weakSelf.projectPathStr error:nil];
            for (NSString *path in aa) {
                if ([path containsString:@"/"]) {
                    continue;
                }
                if ([path.pathExtension isEqualToString:@"xcodeproj"]) {
                    _projectNameStr = [path.lastPathComponent stringByDeletingPathExtension];
                    
                }
            }
        }
        
    }];
}


- (IBAction)selectCer:(id)sender {
    _currentType = 2;
    NSOpenPanel *panel = [[NSOpenPanel alloc] init];
    panel.canChooseDirectories = YES;
    panel.title = @"选取证书路径";
    panel.delegate = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Desktop"]];
    panel.directoryURL = url;
    panel.backgroundColor = NSColor.whiteColor;
    __weak typeof(self) weakSelf = self;
    [panel beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:^(NSModalResponse returnCode) {
        if (returnCode==1) {
            weakSelf.cerPathStr = weakSelf.currentUrl.path;
            weakSelf.cerPath.stringValue = weakSelf.cerPathStr;
        }
        
    }];
}



- (IBAction)selectOut:(id)sender {
    _currentType = 3;
    NSOpenPanel *panel = [[NSOpenPanel alloc] init];
    panel.canChooseDirectories = YES;
    panel.title = @"选取导出路径";
    panel.delegate = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Desktop"]];
    panel.directoryURL = url;
    panel.backgroundColor = NSColor.whiteColor;
    __weak typeof(self) weakSelf = self;
    [panel beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:^(NSModalResponse returnCode) {
        if (returnCode==1) {
            weakSelf.outPathStr = weakSelf.currentUrl.path;
            weakSelf.outPath.stringValue = weakSelf.outPathStr;
        }
        
    }];
}

- (IBAction)startArcchive:(id)sender {
    if (!_projectPathStr) {
        NSAlert *alert = [[NSAlert alloc] init];
        alert.messageText = @"请选择项目路径";
        [alert addButtonWithTitle:@"关闭"];
        [alert beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:nil];

        return;
    }
    if (!_cerPathStr) {
        NSAlert *alert = [[NSAlert alloc] init];
        alert.messageText = @"请选择证书路径";
        [alert addButtonWithTitle:@"关闭"];
        [alert beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:nil];
        return;
    }
    if (!_outPathStr) {
        NSAlert *alert = [[NSAlert alloc] init];
        alert.messageText = @"请选择导出路径";
        [alert addButtonWithTitle:@"关闭"];
        [alert beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:nil];
        return;
    }
    
    
    int enviromentCode = (int)_enviromentBtn.indexOfSelectedItem;
    NSString *enviromentStr = (enviromentCode==0?@"Debug":@"Release");
  NSString *cleanShell = [NSString stringWithFormat:@"xcodebuild \
                          clean -configuration %@",enviromentStr];
    
//    int cleanres = system(cleanShell.UTF8String);//iOS上执行脚本
    BOOL hasBuild = [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/build/%@.xcarchive",_outPathStr,_projectNameStr]];
    NSString *buildShell = [NSString stringWithFormat:@"xcodebuild \
                            archive -workspace %@/%@.xcworkspace \
                            -scheme %@ \
                            -configuration %@ \
                            -archivePath %@/build/%@.xcarchive",_projectPathStr,_projectNameStr,_projectNameStr,enviromentStr,_outPathStr,_projectNameStr];
    NSString *exportShell = [NSString stringWithFormat:@"xcodebuild -exportArchive -archivePath %@/%@.xcarchive \
                             -configuration %@ \
                             -exportPath %@/IPA \
                             -exportOptionsPlist %@ \
                             -allowProvisioningUpdates YES -quiet || exit",[_outPathStr stringByAppendingPathComponent:@"build"],_projectNameStr,enviromentStr,_outPathStr,_cerPathStr];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *cleanres = [self cmd:cleanShell];
        if (!hasBuild) {
            NSString *archiveCode = [self cmd:buildShell];
        }
        NSString *exportCode = [self cmd:exportShell];
        
          if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/IPA/%@.ipa",_outPathStr,_projectNameStr]]) {
              dispatch_async(dispatch_get_main_queue(), ^{
                  NSOpenPanel *panel = [[NSOpenPanel alloc] init];
                  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_outPathStr]];
                  panel.directoryURL = url;
                  panel.backgroundColor = NSColor.whiteColor;
                  __weak typeof(self) weakSelf = self;
                  
                      [panel beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:^(NSModalResponse returnCode) {
                          
                          
                      }];
              });
          }
    });
  
    
}

- (NSString *)cmd:(NSString *)cmd{
   __weak typeof(self)weakSelf = self;
    cmd = [NSString stringWithFormat:@"cd %@;%@",_projectPathStr,cmd];
    // 初始化并设置shell路径
    NSTask *task = [[NSTask alloc] init];
    _currentTask = task;
    [task setLaunchPath: @"/bin/bash"];
    // -c 用来执行string-commands（命令字符串），也就说不管后面的字符串里是什么都会被当做shellcode来执行
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    
    // 新建输出管道作为Task的输出
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    
    // 开始task
    NSFileHandle *file = [pipe fileHandleForReading];
    NSError *err;
   BOOL success = [task launchAndReturnError:&err];
    NSString *result;
    if (success) {
        // 获取运行结果
        NSData *data = [file readDataToEndOfFile];
        [task terminate];
        result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    }
    else{
        [task terminate];
        result = err.domain;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.text.string =  [weakSelf.text.string stringByAppendingFormat:@"\n%@",result];
    });
   
    return result;
}

/* iOS使用
 -(BOOL)dealRes:(int)code{
     if(code==127){
         NSAlert *alert = [[NSAlert alloc] init];
         alert.messageText = @"没有权限";
         [alert addButtonWithTitle:@"关闭"];
         [alert beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:nil];
         return NO;
     }
     if(code==-1){
         NSAlert *alert = [[NSAlert alloc] init];
         [alert addButtonWithTitle:@"关闭"];
         alert.messageText = @"错误";
         [alert beginSheetModalForWindow:[NSApplication sharedApplication].keyWindow completionHandler:nil];
         return NO;
     }
     return YES;
 }
 */


- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

- (BOOL)panel:(id)sender shouldEnableURL:(NSURL *)url API_AVAILABLE(macos(10.6)){
    return YES;
}

- (BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError **)outError API_AVAILABLE(macos(10.6)){
    
    return YES;
}

- (void)panel:(id)sender willExpand:(BOOL)expanding{
    
}

/* Optional - Sent when the user has changed the selection.
*/
- (void)panelSelectionDidChange:(nullable id)sender{
    NSArray *arr =((NSOpenPanel*)sender).URLs;
    if (arr.count) {
        _currentUrl = arr[0];
    }
    
}

- (void)panel:(id)sender didChangeToDirectoryURL:(nullable NSURL *)url API_AVAILABLE(macos(10.6)){
    _currentUrl = url;
}

@end
